package com.photonpay.api.util;

import org.apache.commons.codec.binary.Base64;

import java.nio.charset.StandardCharsets;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

/**
 * @author ：lo-
 * @date ：Created in 2023/11/22 16:37
 */
public class RSAUtil {

    // 定义加密方式
    public static final String KEY_RSA = "RSA";
    // 定义签名算法
    private final static String KEY_RSA_SIGNATURE = "MD5withRSA";

    /**
     * 签名
     * @param encryptedStr 签名串
     * @param privateKey 私钥
     * @return
     */
    public static String sign(String encryptedStr, String privateKey) {
        String str = "";
        try {
            //将私钥加密数据字符串转换为字节数组
            byte[] data = encryptedStr.getBytes(StandardCharsets.UTF_8);
            // 解密由base64编码的私钥
            byte[] bytes = Base64.decodeBase64(privateKey);
            // 构造PKCS8EncodedKeySpec对象
            PKCS8EncodedKeySpec pkcs = new PKCS8EncodedKeySpec(bytes);
            // 指定的加密算法
            KeyFactory factory = KeyFactory.getInstance(KEY_RSA);
            // 取私钥对象
            PrivateKey key = factory.generatePrivate(pkcs);
            // 用私钥对信息生成数字签名
            Signature signature = Signature.getInstance(KEY_RSA_SIGNATURE);
            signature.initSign(key);
            signature.update(data);
            str = Base64.encodeBase64String(signature.sign());
        } catch (Exception e) {
            System.out.println(e.getMessage());
            throw new RuntimeException("签名出错");
        }
        return str;
    }

    /**
     * 验签
     * @param encryptedStr 加密串
     * @param publicKey 公钥
     * @param sign 签名
     * @return true = 通过
     */
    public static boolean verify(String encryptedStr, String publicKey, String sign) {
        boolean flag = false;
        try {
            //将私钥加密数据字符串转换为字节数组
            byte[] data = encryptedStr.getBytes(StandardCharsets.UTF_8);
            // 解密由base64编码的公钥
            byte[] bytes = Base64.decodeBase64(publicKey);
            // 构造X509EncodedKeySpec对象
            X509EncodedKeySpec keySpec = new X509EncodedKeySpec(bytes);
            // 指定的加密算法
            KeyFactory factory = KeyFactory.getInstance(KEY_RSA);
            // 取公钥对象
            PublicKey key = factory.generatePublic(keySpec);
            // 用公钥验证数字签名
            Signature signature = Signature.getInstance(KEY_RSA_SIGNATURE);
            signature.initVerify(key);
            signature.update(data);
            flag = signature.verify(Base64.decodeBase64(sign));
        } catch (Exception e) {
            throw new RuntimeException("公钥验签出错");
        }
        return flag;
    }

}
